// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.repo

import xyz.apiote.bimba.czwek.api.structs.FeedInfoV1
import xyz.apiote.bimba.czwek.api.structs.FeedInfoV2
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale

data class FeedInfo(
	val id: String,
	val name: String,
	val attribution: String,
	val description: String,
	val lastUpdate: LocalDate,
	val qrHost: String,
	val qrIn: QrLocation,
	val qrSelector: String,
	val validSince: LocalDate?,
	val validTill: LocalDate?,
	val cached: Boolean
) {
	constructor(f: FeedInfoV2, cached: Boolean = false) : this(
		f.id,
		f.name,
		f.attribution,
		f.description,
		f.lastUpdate,
		f.qrHost,
		QrLocation.of(f.qrIn),
		f.qrSelector,
		f.validSince,
		f.validTill,
		cached
	)

	constructor(f: FeedInfoV1, cached: Boolean = false) : this(
		f.id,
		f.name,
		f.attribution,
		f.description,
		f.lastUpdate.toLocalDate(),
		"",
		QrLocation.UNKNOWN,
		"",
		null,
		null,
		cached
	)

	fun formatDate(): String {
		return lastUpdate.format(
			DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(Locale.getDefault())
		)
	}
}

fun FeedInfo?.join(other: FeedInfo?): FeedInfo {
	assert(this != null || other != null)

	if (this == null) return other!!
	if (other == null) return this

	return FeedInfo(
		id,
		other.name,
		other.attribution,
		other.description,
		if (lastUpdate.isAfter(other.lastUpdate)) lastUpdate else other.lastUpdate,
		other.qrHost,
		other.qrIn,
		other.qrSelector,
		if (validSince == null || validSince.isAfter(other.validSince)) validSince else other.validSince,
		if (validTill == null || validTill.isAfter(other.validTill)) validTill else other.validTill,
		this.cached && other.cached
	)
}
